document.addEventListener('DOMContentLoaded', function() {
    const urlParams = new URLSearchParams(window.location.search);
    const blogId = urlParams.get('id');
    if (!blogId) {
        alert('博客ID未提供');
        return;
    }

    function fetchBlogDetails() {
        fetch(`http://101.34.242.206:9990/Blogs/getById/${blogId}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    const blog = data.data;
                    document.getElementById('cover').src = blog.coverurl;
                    document.getElementById('title').textContent = blog.title;
                    document.getElementById('author').innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-user"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg> ${blog.author}`;
                    document.getElementById('createtime').innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-calendar"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect><line x1="16" y1="2" x2="16" y2="6"></line><line x1="8" y1="2" x2="8" y2="6"></line><line x1="3" y1="10" x2="21" y2="10"></line></svg> ${new Date(blog.createtime).toLocaleDateString()}`;
                    document.getElementById('views').innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-eye"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" r="3"></circle></svg> ${blog.views || 0} 次浏览`;

                    // 使用marked解析Markdown内容，并使用highlight.js高亮代码
                    const content = document.getElementById('content');
                    content.innerHTML = marked.parse(blog.content);
                    document.querySelectorAll('pre code').forEach((block) => {
                        hljs.highlightElement(block);
                    });

                    generateTOC(content);
                } else {
                    alert('获取博客详情失败');
                }
            })
            .catch(error => console.error('Error fetching blog details:', error));
    }

    function generateTOC(content) {
        const tocContent = document.getElementById('toc-content');
        tocContent.innerHTML = '';

        const headers = content.querySelectorAll('h1, h2, h3, h4, h5, h6');
        headers.forEach((header, index) => {
            header.id = `toc-${index}`;
            const tocItem = document.createElement('a');
            tocItem.href = `#toc-${index}`;
            tocItem.textContent = header.textContent;
            tocItem.classList.add('toc-item');
            tocItem.classList.add(`toc-${header.tagName.toLowerCase()}`);
            tocContent.appendChild(tocItem);
        });
    }

    function fetchComments() {
        fetch(`http://101.34.242.206:9990/Comments/getComment/${blogId}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    displayComments(data.data);
                } else {
                    alert('获取评论失败');
                }
            })
            .catch(error => console.error('Error fetching comments:', error));
    }

    function displayComments(comments) {
        const commentsSection = document.getElementById('comments-section');
        commentsSection.innerHTML = '';

        comments.forEach(comment => {
            const commentElement = document.createElement('div');
            commentElement.className = 'comment';
            commentElement.innerHTML = `
                <img src="${comment.headerurl}" alt="Avatar">
                <div class="comment-body">
                    <h3>${comment.nickname} <span class="comment-time">${new Date(comment.createTime).toLocaleString()}</span></h3>
                    <p>${comment.content}</p>
                </div>
            `;
            commentsSection.appendChild(commentElement);
        });
    }

    document.getElementById('submit-comment').addEventListener('click', function() {
        const commentText = document.getElementById('comment-text').value;
        if (commentText.trim() === '') {
            alert('评论不能为空');
            return;
        }

        const commentData = {
            content: commentText
        };

        fetch(`http://101.34.242.206:9990/Comments/addComment/${blogId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(commentData)
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    document.getElementById('comment-text').value = '';
                    fetchComments();
                } else {
                    alert('提交评论失败');
                }
            })
            .catch(error => console.error('Error submitting comment:', error));
    });

    fetchBlogDetails();
    fetchComments();

    // 复制链接功能
    document.getElementById('copy-link').addEventListener('click', function (event) {
        event.preventDefault();
        const dummy = document.createElement('textarea');
        document.body.appendChild(dummy);
        dummy.value = window.location.href;
        dummy.select();
        document.execCommand('copy');
        document.body.removeChild(dummy);
        alert('链接已复制到剪贴板');
    });

    // 阅读模式按钮点击事件
    document.getElementById('reading-mode-button').addEventListener('click', function() {
        window.location.href = `reading_mode.html?id=${blogId}`;
    });
});



